package com.mornd.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mornd.gulimall.product.entity.SkuImages;
import com.mornd.gulimall.product.entity.SkuInfo;
import com.mornd.gulimall.product.entity.vo.spusave.ImageVo;
import com.mornd.gulimall.product.mapper.SkuImagesMapper;
import com.mornd.gulimall.product.service.ISkuImagesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static cn.hutool.core.collection.IterUtil.isNotEmpty;

/**
 * <p>
 * sku图片 服务实现类
 * </p>
 *
 * @author mornd
 * @since 2023-07-23
 */
@Service
public class SkuImagesServiceImpl extends ServiceImpl<SkuImagesMapper, SkuImages> implements ISkuImagesService {

    /**
     * 保存 sku 图集
     *
     * @param saves
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuImgs(List<SkuInfo> saves) {
        List<SkuImages> skuImages = new ArrayList<>();
        for (SkuInfo save : saves) {
            if (isNotEmpty(save.getSelectedImages())) {

                // 默认图片放在第一位
                ImageVo first = null;
                List<ImageVo> newList = new ArrayList<>();
                for (ImageVo selectedImage : save.getSelectedImages()) {
                    if (selectedImage.getDefaultImg() == 1 && first == null) {
                        first = selectedImage;
                    } else {
                        newList.add(selectedImage);
                    }
                }
                if (first != null) {
                    newList.add(0, first);
                }

                int sort = 0;
                for (ImageVo imageVo : newList) {
                    SkuImages images = new SkuImages();
                    images.setSkuId(save.getSkuId());
                    images.setImgUrl(imageVo.getUrl());
                    images.setDefaultImg(imageVo.getDefaultImg());
                    images.setImgSort(sort++);
                    skuImages.add(images);
                }
            }
        }
        super.saveBatch(skuImages);
    }

    @Override
    public List<SkuImages> geyBySkuId(Long skuId) {
        LambdaQueryWrapper<SkuImages> qw = Wrappers.<SkuImages>lambdaQuery().eq(SkuImages::getSkuId, skuId).orderByAsc(SkuImages::getImgSort);
        return super.list(qw);
    }
}
